package com.example.demo.test;

import com.example.demo.domain.Material;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MaterialQuantityMergeExample {
    public static void main(String[] args) {
        List<Material> materials = createMaterialList();

        // 使用Stream API按照物料编码对物料进行分组，并合并相同编码物料的数量
        /*List<Material> mergedMaterials = materials.stream()
              .collect(Collectors.groupingBy(Material::getCode, Collectors.summingInt(Material::getQuantity)))
              .entrySet().stream()
              .map(entry -> new Material(entry.getKey(), entry.getValue()))
              .collect(Collectors.toList());*/

        List<Material> materialList = materials.stream()
                .collect(Collectors.groupingBy(Material::getCode))
                .entrySet().stream()
                .map(stringListEntry -> {
                    List<Material> value = stringListEntry.getValue();
                    Integer integer = value.stream().mapToInt(Material::getQuantity).sum();
                    return new Material(stringListEntry.getKey(), integer);
                }).collect(Collectors.toList());
        // 输出合并后的物料列表
        //mergedMaterials.forEach(material -> System.out.println("物料编码: " + material.getCode() + ", 数量: " + material.getQuantity()));
        materialList.forEach(material -> System.out.println("物料编码: " + material.getCode() + ", 数量: " + material.getQuantity()));
    }

    private static List<Material> createMaterialList() {
        List<Material> materials = new ArrayList<>();
        materials.add(new Material("M001", 10));
        materials.add(new Material("M002", 15));
        materials.add(new Material("M001", 5));
        materials.add(new Material("M003", 8));
        materials.add(new Material("M002", 7));
        return materials;
    }
}